package com.warehouse.dao.impl;

import com.warehouse.dao.CargoDao;
import com.warehouse.dao.common.HibernateUtil;
import com.warehouse.entity.Admin;
import com.warehouse.entity.Cargo;
import org.hibernate.Query;

import java.util.List;

public class CargoDaoImpl implements CargoDao {
    //增加
    @Override
    public int add(Cargo cargo) {
        try {
            HibernateUtil.currentSession().save(cargo);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
        return 1;
    }

    //修改
    @Override
    public int update(Cargo cargo) {
        try {
            HibernateUtil.currentSession().update(cargo);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
        return 1;
    }

    //删除
    @Override
    public int delete(int id) {
        try {
            //先获取id
            Cargo cargo = (Cargo) HibernateUtil.currentSession().get(Cargo.class, id);
            HibernateUtil.currentSession().delete(cargo);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
        return 1;
    }

    //分页查询
    @Override
    public List<Cargo> allPage(int startPage, int pageSize) {
        Query query = HibernateUtil.currentSession().createQuery("from Cargo");
        query.setFirstResult(startPage);
        query.setMaxResults(pageSize);
        return query.list();
    }

    //计算总条数
    @Override
    public int count() {
        return HibernateUtil.currentSession().createQuery("from Cargo").list().size();
    }

    //根据id查询信息
    @Override
    public Cargo byId(int id) {
        Cargo cargo = (Cargo) HibernateUtil.currentSession().get(Cargo.class, id);
        return cargo;
    }

//    //分页模糊查询
//    @Override
//    public List<Cargo> byAdminNum(int startPage, int pageSize, String name) {
//        Query query = HibernateUtil.currentSession().createQuery("from Cargo c where c.name like '%" + name + "%'");
//        query.setFirstResult(startPage);
//        query.setMaxResults(pageSize);
//        return query.list();
//    }
//
//    //分页模糊查询出来的条数
//    @Override
//    public int countByAdminNum(String name) {
//        return HibernateUtil.currentSession().createQuery("from Cargo c where c.name like '%" + name + "%'").list().size();
//    }


    @Override
    public List<Cargo> byType(int startPage, int pageSize, Integer typeId) {
        Query query = HibernateUtil.currentSession().createQuery("from Cargo c where c.cargotype.id = "+typeId);
        query.setFirstResult(startPage);
        query.setMaxResults(pageSize);
        return query.list();
    }

    @Override
    public int countByType(Integer typeId) {
        return HibernateUtil.currentSession().createQuery("from Cargo c where c.cargotype.id = "+typeId).list().size();
    }
}
